from thoughts.models  import Thought, Witness, Article, ArticleNote 
from django.shortcuts import render_to_response, get_object_or_404 
from django.template  import RequestContext
from thoughts.forms   import ThoughtForm
from books.models     import Book, BookNote
from articles.models  import Article, ArticleNote 
from django.http      import HttpResponseRedirect, Http404
from django.core.urlresolvers       import reverse
from django.views.decorators.csrf   import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from datetime import datetime

def era(request):
    thoughts =  Thought.objects.today().filter(inventor = request.user)
    context = {
        'thoughts' : thoughts,
        'request': request,
        }
    
    return render_to_response(
        'thoughts/era.html',
        context,
        context_instance = RequestContext(request),
    )

def archive(request):
    thoughts =  Thought.objects.filter(inventor = request.user)
    context = {
        'thoughts' : thoughts,
        'request': request,
        }
    
    return render_to_response(
        'thoughts/archive.html',
        context,
        context_instance = RequestContext(request),
    )


@csrf_exempt
def create(request):
    mainform = ThoughtForm(request.POST or None)
    if mainform.is_valid():
        thought = mainform.save(commit=False)
        thought.inventor = request.user
        thought.start_date = None
        thought.save()
        if 'next' in request.POST:
           next = request.POST['next']
        else:
           next = reverse('thought_era')
        return HttpResponseRedirect(next)
    return render_to_response (
        'thoughts/create.html',
        {
         'mainform' : mainform,
        },
        context_instance = RequestContext(request)
        )


@csrf_exempt
def references_list(request):
    bookreferences = Book.objects.filter(user = request.user)
    articlereferences = Article.objects.filter(user = request.user)
    return render_to_response (
        'thoughts/reference_list.html',
         {
         'request':request,
         'bookreferences' : bookreferences,
         'articlereferences' : articlereferences,
         },
         context_instance = RequestContext(request)
        ) 


@csrf_exempt
def toggle_wintnessing(request, thought_id):
    thought = get_object_or_404(Thought,id = thought_id)
    if thought.inventor != request.user: 
        wintess, created = Witness.objects.get_or_create(user=request.user
                                                         , thought= thought)
        if created:
            a=''
        else:
            wintess.delete()  
            #request.user.message_set.create(message = 
            #                            ' You are not witnissing "%s"' % thought)
    else:
        raise ValueError(" You cannot witness yourself ")
    next = request.POST.get('next','')
    if not next:
        next = reverse('thought_era')
    return HttpResponseRedirect(next)


@csrf_exempt
def view_notes(request, thought_id):
    thought = get_object_or_404(Thought,id = thought_id)
    attached_booknotes = BookNote.objects.filter(book__user 
                       = request.user).filter(id__in = thought.book_notes.all())
    attached_articlenotes  =   ArticleNote.objects.filter(article__user = request.user).filter(id__in = thought.article_notes.all())
    booknotes = BookNote.objects.filter(book__user = request.user).exclude(id__in = attached_booknotes.all()) 
    articlenotes = ArticleNote.objects.filter(article__user = request.user).exclude(id__in = attached_articlenotes.all())

    return render_to_response (
        'thoughts/attach_note.html',
        {
         'request': request,
         'thought'  : thought,
         'booknotes' : booknotes,
         'articlenotes': articlenotes,
         'attached_booknotes' : attached_booknotes,
         'attached_articlenotes': attached_articlenotes,
        },
        context_instance = RequestContext(request)
        )


@csrf_exempt
def attach_note(request, thought_id, note_id, note_type):
    #import pdb;pdb.set_trace()
    thought = get_object_or_404(Thought,id = thought_id)
    if note_type == 'book':
        note    = get_object_or_404(BookNote,id = note_id)
        thought.book_notes.add(note)
    else: 
        note    = get_object_or_404(ArticleNote,id = note_id)
        thought.article_notes.add(note)
    
    thought.save()   
    next = request.POST.get('next','')

    if not next:
        next = reverse('thought_vnote', args=[thought_id])
    return HttpResponseRedirect(next)


@csrf_exempt
def unattach_note(request, thought_id, note_id, note_type):
    thought = get_object_or_404(Thought,id = thought_id)
    if note_type == 'book':
        note    = get_object_or_404(BookNote,id = note_id)
        thought.book_notes.remove(note)
    else: 
        note    = get_object_or_404(ArticleNote,id = note_id)
        thought.article_notes.remove(note)
       
    next = request.POST.get('next','')
  
    if not next:
        next = reverse('thought_vnote', args=[thought_id])
    return HttpResponseRedirect(next)

@csrf_exempt
def toggle_publish(request):
    try:
        thought_id = int(request.POST['thought_id'])
    except (KeyError, ValueError):
        raise Http404
    thought = get_object_or_404(Thought,id = thought_id)
    thought.published = True
    thought.published_date = datetime.now() 
    thought.save()
    next = request.POST.get('next','')
    if not next:
        next = reverse('thought_era')
    return HttpResponseRedirect(next)

@csrf_exempt
def update_thought(request, thought_id, dontvalidate):
    thought = get_object_or_404(Thought, id = thought_id)
    next = 'no'
    if dontvalidate == 'yes':
        thoughtform = ThoughtForm(instance = thought)
    else:
        if request.method == "POST":
            thoughtform = ThoughtForm(request.POST, instance = thought )
        else:
            thoughtform = ThoughtForm(instance = thought )
        if thoughtform.is_valid():
            thought.save() 
            next = 'yes'
    return render_to_response(
        'thoughts/update_thought.html',
        {
         'thought_id':thought_id,
         'thoughtform':thoughtform,
         'next': next,
         'dontvalidate': dontvalidate,
        },
        context_instance = RequestContext(request)
        )
